<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>{$activityname}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection" content="telephone=no" />
<link href="{$Think.config.RESOURCEURL}wx_assets/css/common.css{$Think.config.RESOURCE_VER}" rel="stylesheet" type="text/css">
<link href="{$Think.config.RESOURCEURL}wx_assets/micontent/materiaDetail.css{$Think.config.RESOURCE_VER}" rel="stylesheet">
<link href="{$Think.config.RESOURCEURL}wx_assets/love/love.css{$Think.config.RESOURCE_VER}" rel="stylesheet">
<script type="text/javascript" src="{$Think.config.RESOURCEURL}wx_assets/js/zepto.1.1.3.min.js{$Think.config.RESOURCE_VER}"></script>
<script type="text/javascript" src="{$Think.config.RESOURCEURL}wx_assets/js/zepto.alert.js{$Think.config.RESOURCE_VER}"></script>
<script src="{$Think.config.RESOURCEURL}wx_assets/js/util.js{$Think.config.RESOURCE_VER}" type="text/javascript"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="{$Think.config.RESOURCEURL}wx_assets/js/wx_share.js{$Think.config.RESOURCE_VER}" type="text/javascript"></script>
    <style>
        html,body{height:100%;}
    </style>
</head>
<body style="background:#fff">
<div class="head-img" id="headImg">
    <img src="{$weixinInfo.headimgurl}" style="display:none">
    <img src="{$weixinInfo.headimgurl}">
</div>
<div class="index-img" id="love-img">
    <volist name="jsonstr" id="item" key="k">
        <if condition="$item.type eq '1'">
            <img src="{$item.src}"/>
        </if>
        <if condition="$item.type eq '2'">
            <img src="{$item.src}" class="js-btn"/>
        </if>
    </volist>
</div>
<div class="opacity" id="opacity"></div>
<div class="productInfo" id="productInfo">
</div>
<script type="text/html" id="productInfoTpl">
    <div class="main">
        <div class="info">
            <div class="closeDiv"><div class="close" id="close"></div></div>
            <div class="imgDiv" align="center" onclick="product.toDetail('<%=fromCustomerId%>','<%=id%>')">
                <img src="<%=picUrl1[1].picUrl%>">
            </div>
            <div class="p-name" onclick="product.toDetail('<%=fromCustomerId%>','<%=id%>')">
                <div class="title" ><%=name%></div>
                <div class="price">￥<% if(discountedPrice) {%>
                    <%=discountedPrice%>
                    <%} else {%>
                        <%=fixedPrice%>
                    <%}%>
                元</div>
            </div>
        </div>
        <%if(supportSpecification=="1"){%>
            <div class="mod_property" id="prop-list">
            <%if(size && size!='null'){%>
                <dl class="size">
                    <dt><%=sizeUnit%></dt>
                    <%if(sizeObj){
                        for(var i=0;i<sizeObj.length;i++){
                            var name=sizeObj[i];
                    %>
                        <dd data-name="<%=name%>"><%=name%></dd>
                    <%}%>
                    <%}%>
                </dl>
            <%}%>
            <%if(color && color!='null'){%>
                <dl class="color">
                    <dt><%=colorUnit%></dt>
                    <%if(colorObj){
                        for(var i=0;i<colorObj.length;i++){
                            var name=colorObj[i];
                    %>
                        <dd data-name="<%=name%>"><%=name%></dd>
                    <%}%>
                    <%}%>
                </dl>
            <%}%>
            </div>
        <%}%>
        <div class="buyNum">
            <div class="title">购买数量</div>
            <div class="numDiv">
                <a class="sub disabled" tag="sub" id="sub"></a>
                <input type="text" readonly="readonly" value="1" class="num" id="buyNum"/>
                <a class="plus <%if(inventory && supportSpecification=="0" && inventoryCount<2){%>disabled<%}%>" tag="add" id="plus"></a>
            </div>
            <%if(inventory){%>
                <span class="inventory" id="inventory_count" <%if(supportSpecification=="0" && inventoryCount>0){%>style='display:block'<%} else {%>style="display:none"<%}%>>&nbsp;剩余<span id="stock-num"><%=inventoryCount%></span>件</span>
                <div class="soldOut" <%if(supportSpecification=="0" && !inventoryCount){%>style='display:block'<%} else {%>style="display:none"<%}%>></div>
            <%}%>
        </div>
        </div>
        <div class="beSure <%if(inventory && supportSpecification=="0" && !inventoryCount){%>btn_disabled<%}%>" id="buy-now">确定</div>
    </div>
    </script>
<body>
<script>
var baseUrl = '{$Think.config.SERVER_HOST}';
var basePath = 'call.json?customerId={$customerId}&userName={$userName}';
var shareUrl="";
var pros={$prodetail};
var product={
    inventory:0,
    totalInventoryCount:0,
    sku:[],
    ktotal:0,
    total:0,
    buyProperty:"",
    init:function(){
        var maxHeight=$.util.page.getHeight();
        $("#opacity").css("height",maxHeight);
    },
    toDetail:function(customerId,id){
        var p=$.util.getParamAsObject();
        var params={
            "id":id,
            "miUId":"{$fromUId}",
            "qId":"{$qId}",
            "fromGuid":p.fromGuid
        }
        params=encodeURIComponent(JSON.stringify(params));
        location.href= baseUrl+'call.html?customerId='+customerId+'&module=product&method=getProduct&params='+params;
    },
    _initClickEvent: function() {
        var me = this;
        if ((me.inventory == 0 || me.totalInventoryCount > 0 || me.sku.length>0)) {
            $(".sub,.plus").on("click", function(e) {
                me._initBuyNum(e);
            });
            $(".mod_property dd").on("click", function(e) {
                me.statisticSelected(e);
            });
            $("#buy-now").click(function() {
                if(!$(this).hasClass("btn_disabled")){
                    me._initBuy();
                }
            });
        }
        $("#close").click(function(){
            $("#opacity").hide();
            $("#productInfo").css("bottom",($("#productInfo").height()+50)*-1);
        });
    },
    createRecord:function(oid,callback){
        var p=$.util.getParamAsObject();
        p.oid=oid;
        $.req.get("call.json?customerId={$customerId}&module=love&method=saveAnswer",{
            userName:"{$userName}",
            params:p
        },function(data){
            if(!data.code){
               callback && callback(data);
            } else {
                $.util.alert(data.msg);
            }
        });
    },
    submitOrder: function(oid,callback) {
        var me = this;
        var btn=$("#buy-now");
        var payType="wxpay";
        var params = {
            "id":oid,
            "remark":"",
            "sid": -1,
            "type":"buy",
            "fullName":"",
            "address":"",
            "phone": "",
            "paytype": payType,
            "dtype": "delivery"
        }
        $.ajax({
            url: window.basePath,
            dataType: "json",
            type: "POST",
            data: {
                module: 'product',
                method: 'submitOrder',
                params: JSON.stringify(params)
            },
            success: function(data) {
                if (typeof(data.code) !== "undefined") {
                    btn.removeClass("btn_disabled");
                    $.util.alert(data.msg);
                    return;
               }
                 if (payType == "wxpay") {
                    try {
                    var price = data.price;
                    WeixinJSBridge.invoke('getBrandWCPayRequest', data.pkg, function(res) {
                        if (res.err_msg == 'get_brand_wcpay_request:ok') {
                            callback && callback(oid);
                        } else {
                            btn.removeClass("btn_disabled");
                            me.cancelOrder(oid,function() {
                                if (res.err_msg == 'get_brand_wcpay_request:cancel') {
                                    return $.util.alert("操作已取消");
                                } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
                                    return $.util.alert("网络错误发送失败，请稍后再试");
                                } else if (res.err_msg == 'access_control:not_allow' || res.err_msg == 'system:access_denied') {
                                    return $.util.alert("商家尚未开通微信支付");
                                } else {
                                    return $.util.alert(res.err_msg);
                                }
                            });
                        }
                    });
                    } catch (e) {
                        me.cancelOrder(oid,function() {
                        btn.removeClass("btn_disabled");
                        return $.util.alert("操作失败，请确保在微信浏览器中操作");
                    });
                    }
               }  else {
                    btn.removeClass("btn_disabled");
                    $.util.alert("支付方式错误");
               }
            },
            error:function(){
                btn.removeClass("btn_disabled");
                $.util.alert("购买失败");
            }
        });
    },
    cancelOrder: function(oid,callback) {
        var btn=$("#buy-now");
        $.ajax({
            url: window.basePath,
            dataType: "json",
            type: "POST",
            data: {
                module: 'product',
                method: 'cancelWxOrder',
                params: '{"oid":' + oid + '}'
            },
            success: function() {
                btn.removeClass("btn_disabled");
                callback && callback();
            }
        });
    },
    _initBuy: function() {
        var me=this;
        var p=$.util.getParamAsObject();
        var data=me.curData;
        if (!$("#buy-now").hasClass("btn-disabled")) {
            if ($("#prop-list dl").length != 0) {
                var size = $("#prop-list dd.current").size();
                var sku = me.sku;
                var isValidate=true;
                $("#prop-list dl").each(function(){
                    if(!$(this).find("dd").hasClass("current")){
                        $.util.alert('请选择'+$(this).find("dt").text());
                        isValidate=false;
                        return false;
                    }
                });
                if(!isValidate){
                    return false;
                }
            }
            var sizes = '';
            var colors = '';
            var customerId = $.util.getParam("customerId");
            prop = me.buyProperty;
            var params={
                "pids": data.id,
                "type": "buy",
                "qId":p.qId || "",
                "miUId":p.miUId || "",
                "vId":data.vId || "",
                "shareId":"{$sId}",
                "shareFromGuid":p.fromGuid || "",
                "userName":'{$userName}',
                "visitId":"{$visitId}"
            };
            if (prop != null) {
                if (me.buyProperty) {
                    var propItems = prop.split("|");
                    if(propItems.length > 0){
                        sizes = encodeURIComponent(propItems[0]);
                    }
                    if(propItems.length > 1) {
                        colors = encodeURIComponent(propItems[1]);
                    }
                }
                if (sizes) {
                    params.sizes = sizes;
                    params.colors = colors;
                }
            }
            if ($("#stock-num") && $("#stock-num").html() == 0) {
                $.util.alert("库存不足");
                return;
            }
            $.util.pageLoading.show();
            $(this).addClass("btn-disabled");
            $.req.get("call.json?customerId=" + data.fromCustomerId + "&module=product&method=preSubmitOrder", {
                params: $.extend(params, {
                    "sizes": sizes,
                    "colors": colors,
                    "counts": $("#buyNum").val()
                })
            }, function(d) {
                if (d.hasOwnProperty('code')) {
                    $("#buy-now").removeClass("btn_disabled");
                    $.util.alert(d.msg);
                } else {
                    //调用订单提交
                    var oid=d.id;
                    var uParam=$.util.getParamAsObject();
                    $("#close").trigger("click");
                    me.submitOrder(oid,function(){
                       //创建送礼物的记录 
                       me.createRecord(oid,function(data){
                            $.extend(p,{
                                "oid":oid,
                                "actId":"{$actId}",
                                "regId":data.regId,
                                "qId":uParam.qId,
                                "miUId":uParam.miUId,
                                "sId":"{$sId}"
                            });
                            $.util.pageLoading.hide();
                            location.href = baseUrl+'call.html?customerId={$customerId}&module=love&method=answer&params=' + JSON.stringify(p);
                       })
                    });
                }
                $.util.pageLoading.hide();
            });
        }
    },
    statisticSelected: function(e) {
        var me=this;
        var b = $(e.target);
        if (!b.hasClass("current") && !b.hasClass("disabled")) {
            b.addClass("current").siblings().removeClass("current");
            var c = b.parent();
            var selectedCount=$(".mod_property dd.current").size();
            if(selectedCount==me.sku.length){
                var key=[];
                $(".mod_property dd.current").each(function(){
                    key.push($(this).data("name"));
                });
                if(key.length>0){
                    key=key.join("|");
                }
                me.buyProperty=key;
                var stock = me.availSku[key];
                if (stock) {
                    $("#buyNum").val(1);
                    var stockCount = stock.stockCount;
                    $("#stock-num").html(stockCount);
                    $("#buyNum").data("nowKc",stockCount);
                    if(stockCount<2) {
                        $("#plus").addClass("disabled");
                    } else {
                        $("#plus").removeClass("disabled");
                    }
                    if(stockCount>0){
                        $("#inventory_count").show();
                        $(".soldOut").hide();
                    }else {
                        $("#inventory_count").hide();
                        $(".soldOut").show();
                    }
                }
                
                if (me.inventory == 1 && stockCount == 0) {
                    $("#buy-now").addClass("btn_disabled");
                    $("#buy-now").removeClass("btn_strong");

                }
                if (me.inventory == 1 && stockCount > 0) {
                    $("#buy-now").removeClass("btn_disabled");
                    $("#buy-now").addClass("btn_strong")
                }
            }
        }
    },
    _initBuyNum: function(e) {
        var me=this;
        var buyNum = $("#buyNum"),
            target = $(e.target),
            type = target.attr("tag"),
            num = 1 * buyNum.val();
        if (target.hasClass("disabled")) {
            return;
        }
        if (num) {
            if (isNaN(num)) {
                buyNum.val(1);
            } else {
                var total = me.total;
                var ktotal = me.ktotal || 999;
                if ($("#prop-list dl").length != 0) {
                    var size = $("#prop-list dd.current").size();
                    var color = $("#prop-list dl").eq(1).find("dd.current").data("value");
                    var sku = me.sku;
                    var isValidate=true;
                    $("#prop-list dl").each(function(){
                        if(!$(this).find("dd").hasClass("current")){
                            $.util.alert('请选择'+$(this).find("dt").text());
                            isValidate=false;
                            return false;
                        }
                    });
                    if(!isValidate){
                        return false;
                    }
                    ktotal = buyNum.data('nowKc') || 999;
                }
                if (type == "add") {
                    if (ktotal && num < parseInt(ktotal)) {
                        buyNum.val(++num);
                        $("#sub").removeClass("disabled");
                        if(num>=ktotal){
                            $("#plus").addClass("disabled");
                        }
                    }
                } else {
                    if (num > 1) {
                        buyNum.val(--num);
                        $("#plus").removeClass("disabled");
                        if (num < 2) {
                            $("#sub").addClass("disabled");
                        }
                    }
                }
            }
        }
    },
    loadProInfo:function(id){
        var me=this;
        var id=id || "{$pid}";
        if(pros){
            var data=pros[id];
            if(data){
                me.inventory = parseInt(data.inventory || 0);
                me.totalInventoryCount = parseInt(data.inventoryCount || 0);
                me.total=parseInt(data.surplusNum || 0);
                data.inventory=parseInt(data.inventory);
                data.inventoryCount=parseInt(data.inventoryCount);
                if(data.availSku){
                    me.availSku=JSON.parse(data.availSku) || "";
                }
                me.ktotal=parseInt(data.inventoryCount || 0);
                me.color=data.color;
                me.size=data.size;
                me.curData=data;
                var sku=[];
                if (data.size) {
                    sku.push({"pList": data.size, "pName":data.sizeUnit,"availSku":data.availSku});
                }
                if (data.color != null) {
                    var colorUnit = "{$colorUnit}";
                    sku.push({"pList": data.color, "pName":data.colorUnit,"availSku":data.availSku});
                }
                me.sku=sku;
                me.renderPro(data);
                me._initClickEvent();
            }
        }
    },
    renderPro:function(data){
        var me=this;
       if(data){
            if(data.color){
                data.colorObj=JSON.parse(data.color);
            }
            if(data.size){
                data.sizeObj=JSON.parse(data.size);
            }
            if(data.picUrl1&&typeof(data.picUrl1)=='string'){
                data.picUrl1 = JSON.parse(data.picUrl1);
            }
            var html=template("productInfoTpl", data),
                container=$("#productInfo");
            container.html(html);
            var proHeight=container.height();
            var winHeigth=$.util.page.getViewHeight();
            var maxHeight=$.util.page.getHeight();
            $("#productInfo").css("bottom",($("#productInfo").height()+50)*-1);
            setTimeout(function(){
                container.addClass("show")
                         .css("bottom",0);
                $("#opacity").show();
            },10);
       }   
    }
}
var page={
    guid:"{$guid}",
    init:function(){
        var me=this;
        this.clickEvent();
        $("#headImg").click(function(){
            me._goList();
        });
    },
    _goList:function(){
        var p=$.util.getParamAsObject();
        var params={
            "actId":"{$actId}",
            "miUid":p.miUid,
            "qId":"{$qId}",
            "sId":"{$sId}"
        }
        params=encodeURIComponent(JSON.stringify(params));
        location.href= 'call.html?customerId={$customerId}&module=love&method=list&params='+params;
    },
    clickEvent:function(){
        $(".js-btn").click(function(){
            product.loadProInfo();
        });
    },
    getShareUrl:function(){
        var p=$.util.getParamAsObject();
        var shareUrl="";
        var me=this;
        var params={
            "actId":"{$actId}",
            "qId":"{$qId}",
            "miUId":p.miUId,
            "fromGuid":me.guid,
            "sId":"{$sId}"
        };
        params=encodeURIComponent(JSON.stringify(params));
        shareUrl=baseUrl+'call.html?customerId={$customerId}&module=love&scope=1&method=index&params='+params;
        return shareUrl;
    }
}
page.init();
window.onload=function(){
    $("#headImg").addClass("head-img-down");
}
shareUrl=page.getShareUrl();
wx_share.init({
    "title":"{$title}",
    "desc":'{$description}',
    "link":shareUrl,
    "imgUrl":"{$picurl}",
    "pkg":{
        "appId": '{$pkg.appId}',
        "timestamp": {$pkg.timestamp},
        "nonceStr": '{$pkg.nonceStr}',
        "signature": '{$pkg.signature}'
    },
    success:function(config,shareType){
        var p=$.util.getParamAsObject();
        var fromGuid=$.util.getParamByObject("fromGuid") || "";
        var me=this;
        $.req.get("call.json?customerId={$customerId}&module=quan&method=saveShare",{
            params:{
                "qId":"{$qId}",
                "sId":"{$sId}",
                "fromGuid":fromGuid,
                "miUId":"{$fromUId}",
                "shareType":shareType,
                "fromPage":"love_index"
            }
        },function(data){
            if(data && !data.code){
                page.guid=data.guid;
            }
        });
    }
 });
</script>
</body>
</html>